<?php

namespace App\Admin\Actions\Order;

use App\Models\Order;
use Encore\Admin\Actions\RowAction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Pay extends RowAction
{
    public $name = '确认转账';

    public function handle(Order $model, Request $request)
    {
        $data = $request->all([
            "pay_no",
            "money",
        ]);

        DB::beginTransaction();
        try {
            // 修改状态
            if ($model->getHint()->toArray() === $model->getHint()->pay('线下转账确认成功')->toArray()) {
                return $this->response()->error('操作失败! 当前状态不允许确认转账!');
            }

            if ($model->payment_money == $data['money'] * 100) {
                $model->update([
                    'paid_at' => now(),
                    'payment_no' => $data['pay_no'],
                ]);
            }
            DB::commit();

        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->response()->error('操作失败: ' . $exception->getMessage());
        }

        return $this->response()->success('操作成功! ')->refresh();
    }

    public function form()
    {
        $this->text("pay_no", '流水号')->rules('required');
        $this->text("money", '转账金额')->rules('required');
    }
}
